# 定义公共方法区
# Create your models here.
import json
import os.path
import random
import subprocess
import sys
import time

from django_redis import get_redis_connection

from WEB.settings import SMS_SET
# 图片验证码 语音验证码
from libs.captcha.audio import AudioCaptcha
from libs.captcha.image import ImageCaptcha
from libs.ronglian_sms_sdk import SmsSDK


# 发送短信验证码
class SendSMS:
    def __init__(self, mobile, tup_data, tid='1'):
        self.mobile = mobile
        self.tup_data = tup_data
        self.tid = tid

    def send_message(self):
        """
            发送短信验证码
            tid : str 容联云通讯创建的模板 没有只能测试 1号模板
            mobile ：str  手机号1,手机号2
            tup_data ：tup # ('变量1', '变量2') 验证码 时效 {1} {2} 这样的模板中的变量
        """
        set_sms_data = SMS_SET.get("yuntongxun")
        sdk = SmsSDK(set_sms_data.get('accId'), set_sms_data.get('accToken'), set_sms_data.get('appId'))
        resp = sdk.sendMessage(self.tid, self.mobile, self.tup_data)
        dict_resp = json.loads(resp)
        print(resp)
        if dict_resp.get('statusCode') == '000000':
            return True
        else:
            return False


# 图片 音频验证码
class Verification:

    def __init__(self, code_type, uuid):

        self.uuid = uuid
        self.code_type = code_type


    def crete_verift(self):
        """
            img_code redis 库

        """
        # 判断日期文件夹是否存在存在 跳过 否则新建
        now_date = time.strftime("%Y-%m-%d", time.localtime())
        date_file = os.path.exists(f'./static/verify_audio/{now_date}')
        if not date_file:
            os.mkdir(f'./static/verify_audio/{now_date}')
            os.mkdir(f'./static/verify_img/{now_date}')
        dict_code = {}
        redis_conn = get_redis_connection('img_code')
        # 判断如果这个验证码已经生成过 就不再执行
        if redis_conn.get(self.uuid):
            return True
        ver_code = str(random.randint(1000, 9999))
        if self.code_type == 'audio':
            audio_obj = AudioCaptcha()  # voicedir='./libs/data'
            data = audio_obj.generate(ver_code)
            file_ex = os.path.isfile(f'./static/verify_audio/{now_date}/{self.uuid}.wav')
            if file_ex:
                return True
            audio_obj.write(ver_code, f'./static/verify_audio/{now_date}/{self.uuid}.wav')
            dict_code['code'] = ver_code
            dict_code['type'] = '.wav'
            redis_conn.set(self.uuid, json.dumps(dict_code), ex=120)
            assert isinstance(data, bytearray)
            assert bytearray(b'RIFF') in data
            return True

        else:
            if not hasattr(sys, 'pypy_version_info'):
                image_obj = ImageCaptcha()  # fonts=['/libs/data/DroidSansMon.ttf'] 设置字体
                data = image_obj.generate(ver_code)
                image_obj.write(ver_code, f'./static/verify_img/{now_date}/{self.uuid}.png')
                assert hasattr(data, 'read')
                dict_code['code'] = ver_code
                dict_code['type'] = '.png'
                redis_conn.set(self.uuid, json.dumps(dict_code), ex=120)
                return True
            else:
                return False


# 获取ip and MAC 地址
class MacAddress:

    def get_ip():

        import socket
        host_info = {}
        host_info['name'] = socket.gethostname()
        host_info['ip'] = socket.gethostbyname(host_info['name'])

        return host_info

    # 获取mac唯一地址
    def get_max_address():
        import uuid
        mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
        return ":".join([mac[e:e + 2] for e in range(0, 11, 2)])


# IP工具类
class IpUtil:
    # X-Forwarded-For:简称XFF头，它代表客户端，也就是HTTP的请求端真实的IP，只有在通过了HTTP 代理或者负载均衡服务器时才会添加该项。
    @staticmethod
    def get_ip(request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 多次反向代理后会有多个ip值，第一个ip才是真实ip
            # print(x_forwarded_for)
        else:
            ip = request.META.get('REMOTE_ADDR')  # 这里获得代理ip
        return ip